package edu.guigu.serverservice.local;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.telephony.TelephonyManager;

import androidx.annotation.Nullable;

import edu.guigu.serverservice.MainActivity;
import edu.guigu.serverservice.R;

// 前台服务,  通过sartForegroundService()启动
public class ForegroundService extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
        toForegroundService();
    }

    @SuppressLint("ForegroundServiceType")
    private void toForegroundService() {
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        String id = "channel100";
        CharSequence name = "FService";
        NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
        // 让系统创建通知渠道
        notificationManager.createNotificationChannel(channel);
        // TODO: 3
        String channelId = "500";
        int requestCode = 0;
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
        // TODO: 2
        Notification notification = new Notification.Builder(this, channelId)
                .setContentTitle("音乐播放器")
                .setContentText("XXXXXXXXXXXXXXX")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
                .build();
        // TODO: 1 启动前台通知 (前台服务)
        startForeground(1, notification);
        // notificationManager.notify(2, notification);
        // notificationManager.cancel(2);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 删除服务,此方法接受一个布尔值，表示是否也删除状态栏通知。
        // 注意，服务将继续运行。如果在前台运行时停止服务，则会删除其通知。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(Service.STOP_FOREGROUND_REMOVE);
        }
    }
}
